package io.github.junxworks.qt.modules.mm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.github.junxworks.ep.core.Result;
import io.github.junxworks.ep.sys.annotations.EpLog;
import io.github.junxworks.qt.modules.mm.dto.FieldDto;
import io.github.junxworks.qt.modules.mm.service.FieldService;

@RestController
@RequestMapping("/mm/fields")
public class FieldController {

	@Autowired
	private FieldService fieldService;

	@GetMapping()
	public Result queryFieldList(FieldDto dto) {
		return Result.ok(fieldService.queryFieldList(dto));
	}

	@PostMapping()
	@EpLog("模型管理-字段管理-新增字段")
	public Result addField(@RequestBody FieldDto dto) {
		fieldService.addField(dto);
		return Result.ok();
	}

	@PutMapping()
	@EpLog("模型管理-字段管理-编辑字段")
	public Result eidtField(@RequestBody FieldDto dto) {
		fieldService.eidtAndBackupField(dto);
		return Result.ok();
	}

	@DeleteMapping("/{id}")
	@EpLog("模型管理-字段管理-删除字段")
	public Result eidtField(@PathVariable("id") Long id) {
		int i = fieldService.deleteField(id);
		if (i == -1) {
			return Result.warn("字段关联了有效规则，不能删除");
		}
		return Result.ok();
	}

	@GetMapping("/{id}")
	public Result fieldDetail(@PathVariable("id") Long id) {
		return Result.ok(fieldService.queryFieldDetailById(id));
	}

	@PostMapping("/cname")
	public Result getFieldByCName(@RequestBody FieldDto condition) {
		return Result.ok(fieldService.queryFieldDetailByCName(condition.getInnerCName()));
	}

	/**
	 * 检查内部中文名是否存在。普通情况restful接口应该用get方法，由于传入中文，此处建议用post方法传递数据
	 *
	 * @param dto the dto
	 * @return the result
	 */
	@PostMapping("/available-icname")
	public Result checkInnerCName(@RequestBody FieldDto dto) {
		dto.setPageNo(1);
		dto.setPageSize(10);
		return Result.ok(fieldService.queryFieldList(dto).getTotal() == 0);
	}
}
